package com.example.music.aop;

import com.example.music.utils.WebCrossOriginTest;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * @className: WebCrossOrigin
 * @author: chenLin
 * @version: 1.0.0
 * @description:
 * @date: 2022/3/25 10:03
 */
@Component
@Aspect
public class WebCrossOrigin {
    @Before(value = "@annotation(com.example.music.utils.WebCrossOriginTest)")
    public void before(){
        // 如果加上注解 WebCrossOrigin 走前置通知代码
        // 在该接口响应头加上允许, 即可跨域
        try {
            Class<?> aClass = Class.forName("com.example.music.controller.WebServer");
            Method[] declaredMethods = aClass.getDeclaredMethods();
            for (Method crossMethod :declaredMethods){
                // 判断方法上是否有该注解
                if ((crossMethod.isAnnotationPresent(WebCrossOriginTest.class))) {
                    // header加入*不拦截参数
                    HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
                    response.addHeader("Access-Control-Allow-Origin","*");
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}
